package com.issac.fileupload.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/hh/");

    @GetMapping("/index")
    public ModelAndView index(ModelAndView modelAndView){
        modelAndView.setViewName("index2");
        return modelAndView;
    }

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request){
        String format = sdf.format(new Date());
        String realPath = request.getServletContext().getRealPath("/img")+format;
        File folder = new File(realPath);
        if (!folder.exists()){
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder,newName));
            String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/img"+format+newName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    @PostMapping("/uploads")
    public String[] uploads(MultipartFile[] files, HttpServletRequest request){
        List list = new ArrayList();
        String format = sdf.format(new Date());
        String realPath = request.getServletContext().getRealPath("/img")+format;

        File folder = new File(realPath);
        if (!folder.exists()){
            folder.mkdirs();
        }
        for (MultipartFile file : files) {
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(folder,newName));
                String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/img"+format+newName;
                list.add(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return (String[]) list.toArray(new String[0]);
    }
}
